package com.microframework.base.data.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.microframework.base.core.util.UuidUtil;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Date;

@Component
public class ParamFieldParseUtil {
	private static StringRedisTemplate stringRedisTemplate;
	
	@Autowired
	public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
		ParamFieldParseUtil.stringRedisTemplate = stringRedisTemplate;
	}
	
	private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ParamFieldParseUtil.class);
	
	// 支持的日期格式列表
	private static final String[] formats = {
		"yyyy-MM-dd HH:mm:ss",
		"yyyy-MM-dd",
		"yyyy年MM月dd日",
		"yyyy年MM月dd日 HH时mm分ss秒",
		"HH:mm:ss",
		"yyyy/MM/dd",
		"yyyy/MM/dd HH:mm:ss",
		"yyyyMMdd",
		"yyyyMMddHHmmss"
	};

	public static void main(String[] args) {
		// 测试1: 基础类型解析
		testBasicTypes();
		
		// 测试2: 嵌套对象解析
		testNestedObjects();
		
		// 测试3: 数组解析
		testArrays();
		
		// 测试4: 日期类型解析
		testDateTypes();
		
		// 测试5: 值来源测试
		testValueSources();
	}
	
	private static void testBasicTypes() {
		System.out.println("\n=== 测试基础类型解析 ===");
		String jsonContent = "{"
			+ "\"stringField\":\"test\","
			+ "\"intField\":100,"
			+ "\"longField\":9999999999,"
			+ "\"floatField\":1.23,"
			+ "\"doubleField\":1.23456789,"
			+ "\"booleanField\":true"
			+ "}";
			
		List<JSONObject> fields = ParamFieldParseUtil.parseJsonStructure(jsonContent);
		System.out.println(JsonKit.toJson(fields));
	}
	
	private static void testNestedObjects() {
		System.out.println("\n=== 测试嵌套对象解析 ===");
		String jsonContent = "{"
			+ "\"user\":{"
			+ "  \"profile\":{"
			+ "    \"name\":\"John\","
			+ "    \"age\":30"
			+ "  },"
			+ "  \"settings\":{"
			+ "    \"theme\":\"dark\""
			+ "  }"
			+ "}"
			+ "}";
			
		List<JSONObject> fields = ParamFieldParseUtil.parseJsonStructure(jsonContent);
		System.out.println(JsonKit.toJson(fields));
		
		// 测试重建
		JSONObject rebuilt = buildJsonFromFields(fields);
		System.out.println("重建结果:");
		System.out.println(rebuilt.toJSONString());
	}
	
	private static void testArrays() {
		System.out.println("\n=== 测试数组解析 ===");
		String jsonContent = "{"
			+ "\"items\":["
			+ "  {"
			+ "    \"id\":1,"
			+ "    \"name\":\"Item 1\","
			+ "    \"tags\":[\"tag1\",\"tag2\"]"
			+ "  }"
			+ "],"
			+ "\"simpleArray\":[1,2,3]"
			+ "}";
			
		List<JSONObject> fields = ParamFieldParseUtil.parseJsonStructure(jsonContent);
		System.out.println(JsonKit.toJson(fields));
		
		// 测试数组路径取值
		String inputJson = "{"
			+ "\"items\":["
			+ "  {\"id\":100,\"name\":\"New Item\"},"
			+ "  {\"id\":200,\"name\":\"Another Item\"}"
			+ "]"
			+ "}";
		JSONObject valueResult = parseValuesByFields(fields, inputJson);
		System.out.println("数组取值结果:");
		System.out.println(valueResult.toJSONString());
	}
	
	private static void testDateTypes() {
		System.out.println("\n=== 测试日期类型解析 ===");
		String jsonContent = "{"
			+ "\"createTime\":\"2024-03-14 15:30:00\","
			+ "\"updateDate\":\"2024-03-14\","
			+ "\"timestamp\":\"2024-03-14T15:30:00.000\""
			+ "}";
			
		List<JSONObject> fields = ParamFieldParseUtil.parseJsonStructure(jsonContent);
		System.out.println(JsonKit.toJson(fields));
		
		// 测试日期格式转换
		String inputJson = "{"
			+ "\"createTime\":\"2024/03/14 15:30:00\","
			+ "\"updateDate\":\"20240314\","
			+ "\"timestamp\":\"2024年03月14日 15时30分00秒\""
			+ "}";
		JSONObject valueResult = parseValuesByFields(fields, inputJson);
		System.out.println("日期转换结果:");
		System.out.println(valueResult.toJSONString());
	}
	
	private static void testValueSources() {
		System.out.println("\n=== 测试值来源 ===");
		// 创建测试字段
		List<JSONObject> fields = new ArrayList<>();
		
		// 1. 输入值
		JSONObject inputField = new JSONObject();
		inputField.put("name", "inputField");
		inputField.put("identifier", "data.input");
		inputField.put("type", "string");
		inputField.put("fieldValueFormSrc", "input");
		fields.add(inputField);
		
		// 2. 常量值
		JSONObject constantField = new JSONObject();
		constantField.put("name", "constantField");
		constantField.put("identifier", "data.constant");
		constantField.put("type", "string");
		constantField.put("fieldValueFormSrc", "constant");
		constantField.put("defaultValue", "固定值");
		fields.add(constantField);
		
		// 3. 系统时间
		JSONObject dateField = new JSONObject();
		dateField.put("name", "dateField");
		dateField.put("identifier", "data.date");
		dateField.put("type", "dateString");
		dateField.put("fieldValueFormSrc", "curSystemDate");
		dateField.put("dateFieldFormatSrc", "select");
		dateField.put("dateFieldFormat", "yyyy-MM-dd HH:mm:ss");
		fields.add(dateField);
		
		String inputJson = "{\"data\":{\"input\":\"输入值\"}}";
		JSONObject valueResult = parseValuesByFields(fields, inputJson);
		System.out.println("不同来源取值结果:");
		System.out.println(valueResult.toJSONString());
	}
	
	/**
	 * 解析JSON结构为字段列表
	 */
	public static List<JSONObject> parseJsonStructure(String jsonContent) {
		List<JSONObject> fields = new ArrayList<>();
		try {
			Object jsonObj = JSON.parse(jsonContent);
			parseObject(jsonObj, "", fields);
		} catch (Exception e) {
			throw new RuntimeException("JSON解析失败: " + e.getMessage());
		}
		return fields;
	}

	/**
	 * 递归解析对象结构
	 */
	private static void parseObject(Object obj, String parentPath, List<JSONObject> fields) {
		if (obj == null) {
			addField(fields, parentPath, "string", null);
			return;
		}

		if (obj instanceof JSONObject) {
			JSONObject jsonObj = (JSONObject) obj;
			for (Map.Entry<String, Object> entry : jsonObj.entrySet()) {
				String currentPath = parentPath.isEmpty() ? entry.getKey() : parentPath + "." + entry.getKey();
				Object value = entry.getValue();
				
				if (value instanceof JSONObject) {
					addField(fields, currentPath, "object", JSON.toJSONString(value));
					parseObject(value, currentPath, fields);
				} else if (value instanceof JSONArray) {
					addField(fields, currentPath, "array", JSON.toJSONString(value));
					JSONArray array = (JSONArray) value;
					if (!array.isEmpty()) {
						parseObject(array.get(0), currentPath + "[0]", fields);
					}
				} else {
					addField(fields, currentPath, determineType(value), value);
				}
			}
		} else if (obj instanceof JSONArray) {
			JSONArray array = (JSONArray) obj;
			if (!array.isEmpty()) {
				parseObject(array.get(0), parentPath + "[0]", fields);
			}
		} else {
			addField(fields, parentPath, determineType(obj), obj);
		}
	}

	/**
	 * 确定字段类型
	 */
	private static String determineType(Object value) {
		if (value == null) return "string";
		
		if (value instanceof Integer) {
			return "int";
		}
		if (value instanceof Long) return "long";
		if (value instanceof Float) return "float";
		if (value instanceof Double) return "double";
		if (value instanceof Boolean) return "boolean";
		if (value instanceof String) {
			String strValue = (String) value;
			// 尝试判断是否为日期格式
			if (isDateString(strValue)) {
				// 根据格式判断具体日期类型
				if (strValue.contains(":")) {
					if (strValue.contains(".") || strValue.contains("T")) {
						return "timestampString";
					}
					return "dateString";
				}
				return "date";
			}
			return "string";
		}
		
		return "string";
	}

	/**
	 * 添加字段到列表
	 */
	private static void addField(List<JSONObject> fields, String path, String type, Object defaultValue) {
		String fieldName = path.contains(".") ? 
			path.substring(path.lastIndexOf(".") + 1) : 
			path.contains("[") ? 
				path.substring(0, path.indexOf("[")) : 
				path;
				
		JSONObject field = new JSONObject();
		field.put("name", fieldName);
		field.put("identifier", path);
		field.put("type", type);
		// 设置默认的值来源
		if (type.contains("date")) {
			field.put("fieldValueFormSrc", "curSystemDate");
			field.put("dateFieldFormatSrc", "select"); // 日期格式来源: select-下拉选择, input-自定义输入
		} else {
			field.put("fieldValueFormSrc", "input"); // input-输入, constant-常量, OLTP-数据库, redis-缓存
		}
		
		// 根据类型设置默认值
		if (defaultValue == null) {
			switch (type) {
				case "int":
				case "long":
					defaultValue = 0;
					break;
				case "float":
				case "double":
					defaultValue = 0.0;
					break;
				case "boolean":
					defaultValue = false;
					break;
				case "array":
					defaultValue = "[]";
					break;
				case "object":
					defaultValue = "{}";
					break;
				case "date":
				case "dateString":
				case "timestampString":
					if ("curSystemDate".equals(field.getString("fieldValueFormSrc"))) {
						defaultValue = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
							.format(new java.util.Date());
					} else {
						defaultValue = "";
					}
					break;
				default:
					defaultValue = "";
			}
		}
		field.put("defaultValue", defaultValue);
		field.put("required", "0");
		
		// 设置日期相关属性
		if (type.contains("date")) {
			field.put("dateFieldFormat", "yyyy-MM-dd HH:mm:ss");
			// 添加日期格式选项
			JSONArray dateFormats = new JSONArray();
			dateFormats.add("yyyy-MM-dd");
			dateFormats.add("yyyy-MM-dd HH:mm:ss");
			dateFormats.add("yyyy年MM月dd日");
			dateFormats.add("yyyy年MM月dd日 HH时mm分ss秒");
			dateFormats.add("HH:mm:ss");
			dateFormats.add("HH时mm分ss秒");
			dateFormats.add("yyyy/MM/dd");
			dateFormats.add("yyyy/MM/dd HH:mm:ss");
			dateFormats.add("yyyyMMdd");
			dateFormats.add("yyyyMMddHHmmss");
			field.put("dateFormats", dateFormats);
		} else {
			field.put("dateFieldFormat", null);
		}
		
		field.put("fieldDecimalPoint", type.equals("float") || type.equals("double") ? 2 : null);
		
		// 添加OLTP相关属性
		if ("OLTP".equals(field.getString("fieldValueFormSrc"))) {
			field.put("datasourceId", null);
			field.put("sql", null);
		}
		
		// 添加Redis相关属性
		if ("redis".equals(field.getString("fieldValueFormSrc"))) {
			field.put("redisKey", null);
		}
		
		field.put("description", "");
		fields.add(field);
	}

	/**
	 * 简单判断是否为日期字符串
	 */
	private static boolean isDateString(String value) {
		// 简单的日期格式判断，可以根据需要扩展
		String datePattern = "^\\d{4}(-|/)?\\d{2}(-|/)?\\d{2}(\\s\\d{2}:\\d{2}(:\\d{2})?)?$";
		return value.matches(datePattern);
	}

	/**
	 * 根据字段列表构建JSON
	 */
	public static JSONObject buildJsonFromFields(List<JSONObject> fields) {
		JSONObject result = new JSONObject();
		
		for (JSONObject field : fields) {
			String identifier = field.getString("identifier");
			String type = field.getString("type");
			Object defaultValue = field.get("defaultValue");
			
			// 处理嵌套路径
			String[] paths = identifier.split("\\.");
			JSONObject current = result;
			
			// 遍历路径构建嵌套结构
			for (int i = 0; i < paths.length; i++) {
				String path = paths[i];
				boolean isLast = (i == paths.length - 1);
				
				// 处理数组路径，如: items[0]
				if (path.contains("[")) {
					String arrayName = path.substring(0, path.indexOf("["));
					if (!current.containsKey(arrayName)) {
						current.put(arrayName, new JSONArray());
					}
					JSONArray array = current.getJSONArray(arrayName);
					
					// 获取数组索引
					int index = Integer.parseInt(path.substring(
						path.indexOf("[") + 1, 
						path.indexOf("]")
					));
					
					// 确保数组有足够的长度
					while (array.size() <= index) {
						array.add(new JSONObject());
					}
					
					if (isLast) {
						array.set(index, convertValue(type, defaultValue));
					} else {
						if (!(array.get(index) instanceof JSONObject)) {
							array.set(index, new JSONObject());
						}
						current = array.getJSONObject(index);
					}
				} else {
					if (isLast) {
						current.put(path, convertValue(type, defaultValue));
					} else {
						if (!current.containsKey(path)) {
							current.put(path, new JSONObject());
						}
						current = current.getJSONObject(path);
					}
				}
			}
		}
		
		return result;
	}

	/**
	 * 根据类型转换值
	 */
	private static Object convertValue(String type, Object value) {
		if (value == null) {
			// 返回类型对应的默认值
			switch (type) {
				case "int":
				case "long":
					return 0;
				case "float":
				case "double":
					return 0.0;
				case "boolean":
					return false;
				default:
					return "";
			}
		}
		
		try {
			switch (type) {
				case "int":
					return Integer.parseInt(value.toString());
				case "long":
					return Long.parseLong(value.toString());
				case "float":
					return Float.parseFloat(value.toString());
				case "double":
					return Double.parseDouble(value.toString());
				case "boolean":
					return Boolean.parseBoolean(value.toString());
				case "array":
					return JSON.parseArray(value.toString());
				case "object":
					return JSON.parseObject(value.toString());
				case "date":
				case "dateString":
				case "timestampString":
					// 统一日期格式
					if (value instanceof java.util.Date) {
						String format = "yyyy-MM-dd HH:mm:ss";
						if (type.equals("date")) {
							format = "yyyy-MM-dd";
						} else if (type.equals("timestampString")) {
							format = "yyyy-MM-dd'T'HH:mm:ss.SSS";
						}
						return new java.text.SimpleDateFormat(format).format(value);
					}
					return value.toString();
				default:
					return value.toString();
			}
		} catch (Exception e) {
			// 转换失败返回默认值
			return convertValue(type, null);
		}
	}

	/**
	 * 根据字段列表构建JSON
	 */
	public static JSONObject parseValuesByFields(List<JSONObject> fields, String inputJson) {
		JSONObject result = new JSONObject();
		JSONObject input = null;
		
		try {
			input = JSON.parseObject(inputJson);
		} catch (Exception e) {
			log.error("Failed to parse input json", e);
		}
		
		for (JSONObject field : fields) {
			String identifier = field.getString("identifier");
			String type = field.getString("type");
			String fieldValueFormSrc = field.getString("fieldValueFormSrc");
			String dateFieldFormatSrc = field.getString("dateFieldFormatSrc");
			String dateFieldFormat = field.getString("dateFieldFormat");
			String defaultValue = field.getString("defaultValue");
			Integer fieldDecimalPoint = field.getInteger("fieldDecimalPoint");
			
			// 根据不同的值来源处理
			Object value;
			switch (fieldValueFormSrc) {
				case "input":
					// 从输入JSON中获取值,如果input为空或获取不到值则使用默认值
					value = (input == null || input.isEmpty()) ? defaultValue : getValueFromPath(input, identifier);
					// 如果仍然获取不到值,使用默认值
					if (value == null) {
						value = defaultValue;
					}
					break;
				case "constant":
					// 使用默认值
					value = defaultValue;
					break;
				case "curSystemDate":
					// 获取当前系统时间
					if (type.contains("date")) {
						String format = "yyyy-MM-dd HH:mm:ss";
						// 根据日期格式来源处理
						if ("select".equals(dateFieldFormatSrc)) {
							format = dateFieldFormat;
						}
						value = new java.text.SimpleDateFormat(format)
							.format(new java.util.Date());
					} else if ("long".equals(type)) {
						value = System.currentTimeMillis();
					} else {
						value = new java.util.Date();
					}
					break;
				case "OLTP":
					// 从数据库获取值
					String datasourceId = field.getString("datasourceId");
					String sql = field.getString("sql");
					if (datasourceId != null && sql != null) {
						value = getValueFromDatabase(identifier,datasourceId, sql);
					} else {
						value = null;
					}
					break;
				case "redis":
					// 从Redis获取值
					String redisKey = field.getString("redisKey");
					if (redisKey != null) {
						value = getValueFromRedis(redisKey);
					} else {
						value = null;
					}
					break;
				default:
					value = field.get("defaultValue");
			}
			
			// 处理数值类型的小数位数
			if ((type.equals("float") || type.equals("double")) && fieldDecimalPoint != null) {
				if (value != null) {
					try {
						double numValue = Double.parseDouble(value.toString());
						value = String.format("%." + fieldDecimalPoint + "f", numValue);
					} catch (Exception e) {
						// 转换失败使用原值
					}
				}
			}
			
			// 处理日期格式
			if (type.contains("date") && value != null) {
				try {
					// 如果值是日期字符串，尝试转换格式
					java.util.Date date = parseDate(value.toString());
					if (date != null) {
						String format = "yyyy-MM-dd HH:mm:ss";
						if ("select".equals(dateFieldFormatSrc)) {
							format = dateFieldFormat;
						}
						value = new java.text.SimpleDateFormat(format).format(date);
					}
				} catch (Exception e) {
					// 转换失败使用原值
				}
			}
			
			// 设置值到结果JSON中
			setValueToPath(result, identifier, convertValue(type, value));
		}
		
		return result;
	}

	/**
	 * 从数据库获取值
	 */
	private static Object getValueFromDatabase(String filedIdentifier,String datasourceId, String sql) {
		if (datasourceId == null || sql == null || sql.trim().isEmpty()) {
			return null;
		}
		
		try {
			// 防止SQL注入
			if (!sql.toLowerCase().startsWith("select")) {
				log.warn("Invalid SQL query attempted: {}", sql);
				return null;
			}

			com.jfinal.plugin.activerecord.Record record=Db.use(datasourceId).findFirst(sql);
			if(record!=null) {
				 return record.getObject(filedIdentifier);
			}
		} catch (Exception e) {
			log.error("Database query failed for datasourceId: " + datasourceId, e);
		}
		return null;
	}
	
	/**
	 * 从Redis获取值
	 */
	private static Object getValueFromRedis(String redisKey) {
		if (redisKey == null || redisKey.trim().isEmpty()) {
			return null;
		}
		
		try {
			if (stringRedisTemplate == null) {
				log.error("StringRedisTemplate not initialized");
				return null;
			}
			
			// 从Redis获取值
			String value = stringRedisTemplate.opsForValue().get(redisKey);
			if (value == null) {
				log.warn("No value found in Redis for key: {}", redisKey);
			}
			return value;
		} catch (Exception e) {
			log.error("Failed to get value from Redis for key: " + redisKey, e);
			return null;
		}
	}
	
	/**
	 * 解析日期字符串
	 */
	public static java.util.Date parseDate(String dateStr) {
		if (dateStr == null || dateStr.trim().isEmpty()) {
			return null;
		}
		
		// 使用线程安全的日期格式化工具
		java.text.DateFormat[] formatters = new java.text.DateFormat[formats.length];
		for (int i = 0; i < formats.length; i++) {
			formatters[i] = new java.text.SimpleDateFormat(formats[i]);
			((java.text.SimpleDateFormat)formatters[i]).setLenient(false);
		}
		
		for (java.text.DateFormat formatter : formatters) {
			try {
				return formatter.parse(dateStr);
			} catch (Exception e) {
				// 尝试下一个格式
			}
		}
		return null;
	}

	/**
	 * 从JSON对象中获取指定路径的值
	 */
	private static Object getValueFromPath(JSONObject json, String path) {
		if (json == null || path == null || path.trim().isEmpty()) {
			return null;
		}
		
		String[] paths = path.split("\\.");
		Object current = json;
		
		for (String p : paths) {
			if (current == null || p.trim().isEmpty()) {
				return null;
			}
			
			// 处理数组路径
			if (p.contains("[")) {
				String arrayName = p.substring(0, p.indexOf("["));
				if (!(current instanceof JSONObject)) {
					return null;
				}
				JSONObject jsonObj = (JSONObject) current;
				if (!jsonObj.containsKey(arrayName)) {
					return null;
				}
				JSONArray array = jsonObj.getJSONArray(arrayName);
				
				try {
					int index = Integer.parseInt(p.substring(
						p.indexOf("[") + 1, 
						p.indexOf("]")
					));
					if (index < 0 || index >= array.size()) {
						log.warn("Array index out of bounds: {}", index);
						return null;
					}
					current = array.get(index);
				} catch (NumberFormatException e) {
					log.warn("Invalid array index format in path: {}", p);
					return null;
				}
			} else {
				if (!(current instanceof JSONObject)) {
					return null;
				}
				current = ((JSONObject) current).get(p);
			}
		}
		
		return current;
	}

	/**
	 * 设置值到指定路径
	 */
	private static void setValueToPath(JSONObject json, String path, Object value) {
		if (json == null || path == null || path.trim().isEmpty()) {
			return;
		}
		
		String[] paths = path.split("\\.");
		JSONObject current = json;
		
		for (int i = 0; i < paths.length; i++) {
			String p = paths[i];
			if (p.trim().isEmpty()) {
				continue;
			}
			boolean isLast = (i == paths.length - 1);
			
			if (p.contains("[")) {
				String arrayName = p.substring(0, p.indexOf("["));
				JSONArray array;
				if (!current.containsKey(arrayName)) {
					array = new JSONArray();
					current.put(arrayName, array);
				} else {
					Object existingValue = current.get(arrayName);
					if (!(existingValue instanceof JSONArray)) {
						array = new JSONArray();
						current.put(arrayName, array);
					} else {
						array = (JSONArray) existingValue;
					}
				}
				
				try {
					int index = Integer.parseInt(p.substring(
						p.indexOf("[") + 1, 
						p.indexOf("]")
					));
					if (index < 0) {
						log.warn("Negative array index: {}", index);
						return;
					}
					
					// 确保数组有足够的长度
					while (array.size() <= index) {
						// 根据是否为最后一个路径决定添加的默认值
						if (isLast) {
							array.add(null);
						} else {
							array.add(new JSONObject());
						}
					}
					
					if (isLast) {
						array.set(index, value);
					} else {
						if (!(array.get(index) instanceof JSONObject)) {
							array.set(index, new JSONObject());
						}
						current = array.getJSONObject(index);
					}
				} catch (NumberFormatException e) {
					log.warn("Invalid array index format in path: {}", p);
					return;
				}
			} else {
				if (isLast) {
					current.put(p, value);
				} else {
					if (!current.containsKey(p)) {
						current.put(p, new JSONObject());
					}
					Object next = current.get(p);
					if (!(next instanceof JSONObject)) {
						next = new JSONObject();
						current.put(p, next);
					}
					current = (JSONObject) next;
				}
			}
		}
	}

	/**
	 * 将输入参数赋值到字段列表中
	 * @param fields 字段列表
	 * @param inputJson 输入JSON
	 * @return 赋值后的字段列表
	 */
	public static List<JSONObject> assignValuesToFields(List<JSONObject> fields, String inputJson) {
		if (fields == null || fields.isEmpty()) {
			return fields;
		}
		
		try {
			JSONObject input = null;
			try {
				input = JSON.parseObject(inputJson);
			} catch (Exception e) {
				log.error("Failed to parse input json", e);
			}
			
			for (JSONObject field : fields) {
				String identifier = field.getString("identifier");
				String fieldValueFormSrc = field.getString("fieldValueFormSrc");
				String type = field.getString("type");
				String dateFieldFormatSrc = field.getString("dateFieldFormatSrc");
				String dateFieldFormat = field.getString("dateFieldFormat");
				String defaultValue = field.getString("defaultValue");
				Integer fieldDecimalPoint = field.getInteger("fieldDecimalPoint");
				
				// 根据来源类型处理赋值
				Object value;
				switch (fieldValueFormSrc) {
					case "input":
						// 从输入JSON中获取值,如果input为空或获取不到值则使用默认值
						value = (input == null || input.isEmpty()) ? defaultValue : getValueFromPath(input, identifier);
						// 如果仍然获取不到值,使用默认值
						if (value == null) {
							value = defaultValue;
						}
						break;
					case "constant":
						value = defaultValue;
						break;
					case "uuid":
						value = UuidUtil.getUUID32();
						break;
					case "curSystemDate":
						String format = field.getString("dateFieldFormat");
						value = new java.text.SimpleDateFormat(format).format(new Date());
						break;
					case "OLTP":
						value = getValueFromDatabase(identifier, field.getString("datasourceId"), field.getString("sql"));
						break;
					case "redis":
						value = getValueFromRedis(field.getString("redisKey"));
						break;
					default:
						log.warn("Unsupported field value source: {}", fieldValueFormSrc);
						continue;
				}
				
				// 处理小数位数
				if (fieldDecimalPoint != null && value != null) {
					try {
						double numValue = Double.parseDouble(value.toString());
						value = String.format("%." + fieldDecimalPoint + "f", numValue);
					} catch (Exception e) {
						// 转换失败使用原值
					}
				}
				
				// 处理日期格式
				if (type.contains("date") && value != null) {
					try {
						Date date = parseDate(value.toString());
						if (date != null) {
							String dateFormat = "yyyy-MM-dd HH:mm:ss";
							if ("select".equals(dateFieldFormatSrc)) {
								dateFormat = dateFieldFormat;
							}
							value = new java.text.SimpleDateFormat(dateFormat).format(date);
						}
					} catch (Exception e) {
						// 转换失败使用原值
					}
				}
				
				// 设置转换后的值
				field.put("value", convertValue(type, value));
			}
			
			return fields;
		} catch (Exception e) {
			log.error("Failed to assign values to fields", e);
			return fields;
		}
	}
}
